<template>
  <div class="app-container">
    <div class="pull-right">
      <el-button
        v-permission="['Admin.Remote.Update']"
        :disabled="managerConnectionStatus!==1"
        :loading="isSubmitLoading"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-open"
        @click="applyPortConfig()"
      >下发并同步
      </el-button>
    </div>
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="150px">
      <el-form-item label="网关ID">
        <div>{{ model.id }}</div>
      </el-form-item>
      <!--<el-form-item label="读取网关SN">
        <div>{{ model.sn || '无' }}</div>
      </el-form-item>-->
      <el-form-item label="所在地区" prop="province">
        <div v-if="!isEdit" class="static-text">
          {{ model.province||""}} {{model.city||""}} {{model.region||"" }}
        </div>
        <el-cascader
          v-if="isEdit"
          v-model="selectedOptions"
          :options="options"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="公司名称" prop="company">
        <div v-if="!isEdit" class="static-text">{{ model.company }}</div>
        <el-input v-if="isEdit" v-model="model.company" placeholder="公司名称"/>
      </el-form-item>
      <el-form-item label="网关编码" prop="deviceCode">
        <div v-if="!isEdit" class="static-text">{{ model.deviceCode }}</div>
        <el-input v-if="isEdit" v-model="model.deviceCode" placeholder="网关编码"/>
      </el-form-item>
      <el-form-item label="详细位置" prop="detailAddress">
        <div v-if="!isEdit" class="static-text">{{ model.detailAddress }}</div>
        <el-input v-if="isEdit" v-model="model.detailAddress" placeholder="详细位置"/>
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <div v-if="!isEdit" class="static-text">{{ model.contact || '无' }}</div>
        <el-input v-if="isEdit" v-model="model.contact" placeholder="联系方式"/>
      </el-form-item>
      <!--<el-form-item label="网管地址" prop="managerIp">
        <div v-if="!isEdit" class="static-text">{{ model.managerIp }}</div>
        <el-input v-if="isEdit" v-model="model.managerIp" placeholder="网管地址"/>
      </el-form-item>-->
      <el-form-item>
        <el-button v-permission="['Admin.Remote.Update']" v-if="!isEdit" type="primary" @click="isEdit= !isEdit">编辑</el-button>
        <el-button v-permission="['Admin.Remote.Update']" v-if="isEdit" type="default" @click="cancel">取消</el-button>
        <el-button v-permission="['Admin.Remote.Update']" v-if="isEdit" :loading="isSubmitLoading" type="primary" @click="updateGateway">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { applyPortConfig } from "@/api/gateway";
  import { getGateway, updateGateway } from "@/api/gateway";
  import { regionData, CodeToText, TextToCode } from 'element-china-area-data'

  export default {
    props: {
      managerConnectionStatus: {
        type: Number,
        default: undefined
      }
    },
    data() {
      return {
        isSubmitLoading: false,
        model: {
          deviceCode: '01',
          // managerIp: '1.1.1.1'
        },
        gatewayId: undefined,
        isEdit: false,
        options: regionData,
        modelRules: {
          deviceCode: [{ required: true, trigger: "blur", message: "请输入网关编码" }],
          province: [{ required: true, trigger: "change", message: "请选择所在地区" }],
          // detailAddress: [{ required: true, trigger: "blur", message: "请输入详细地址" }],
          // areaCode: [{ required: true, trigger: "blur", message: "请输入地址编码" }],
          company: [{ required: true, trigger: "blur", message: "请输入公司名称" }]
        }
      };
    },
    computed: {
      selectedOptions: {
        // getter
        get: function() {
          const areaArray = [];
          if (Object.keys(this.model).length) {
            if (this.model.province) {
              areaArray[0] = TextToCode[this.model.province].code;
            }
            if (this.model.city) {
              areaArray[1] = TextToCode[this.model.province][this.model.city].code;
            }
            if (this.model.region) {
              areaArray[2] = TextToCode[this.model.province][this.model.city][this.model.region].code;
            }
          }
          return areaArray;
        },
        // setter
        set: function(newValue) {
          console.log(newValue);
          this.model.province = CodeToText[newValue[0]];
          this.model.city = CodeToText[newValue[1]];
          this.model.region = CodeToText[newValue[2]];
          this.model.areaCode = newValue[2];
        }
      }
    },
    created() {
    },
    methods: {
      getGateway(gatewayId) {
        this.gatewayId = gatewayId;
        getGateway(gatewayId).then(result => {
          this.model = result;
        });
      },
      cancel() {
        this.isEdit = false;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
        this.getGateway(this.gatewayId);
      },
      updateGateway() {
        this.isSubmitLoading = true;
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            updateGateway(this.model)
              .then(() => {
                this.$emit('save');
                this.$message({
                  message: "编辑成功",
                  type: "success"
                });
                this.getGateway(this.gatewayId);
                this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
                this.isEdit = false;
              })
              .catch(() => {
                this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
              });
          } else {
            this.isSubmitLoading = false;
            this.$message({
              message: this.$t("formIsNotValidMessage"),
              type: "warning"
            });
          }
        });
      },
      applyPortConfig() {
        this.$confirm("该操作将同步并应用配置， 是否继续?", "确定执行同步并应用配置操作吗？", { type: "warning" })
          .then(() => {
            const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
            applyPortConfig(this.gatewayId)
              .then(() => {
                this.$message({
                  message: "同步并应用配置成功",
                  type: "success"
                });
                loading.close();
              })
              .catch(() => {
                loading.close();
              });
          })
          .catch(() => {

          });
      }
    }
  };
</script>

<style lang="scss">
  .el-cascader {
    display: block;
    max-width: 400px;
  }
  .pull-right{
    position: relative;
    z-index: 1;
    float: right;
  }
  .el-input {
    max-width: 400px;
  }
</style>
